from itpay.core.agency import agency_service, agency_stat_service
from itpay.core.mch import service as mch_service
from itpay.core.agency.const import DEFAULT_AVATAR


def wrapper_receipt_address(obj, wrap_agency=False, wrap_reached_daily_limit=False, wrap_available=False):
    if wrap_agency:
        agency_id = obj['agency_id']
        del obj['agency_id']
        agency = agency_service.get_agency_by_id(agency_id)
        obj['agency'] = agency
        if agency.get('parent_id'):
            parent_agency = agency_service.get_agency_by_id(agency['parent_id'])
            agency['parent'] = parent_agency
    if wrap_reached_daily_limit:
        obj['reached_daily_limit'] = obj['daily_amount_limit'] and obj['daily_amount'] >= obj['daily_amount_limit']
    if wrap_available:
        obj['available'] = obj['status'] and (
                not obj['daily_amount_limit'] or obj['daily_amount'] < obj['daily_amount_limit'])
    return obj


def wrapper_agency_info(obj, wrap_level=False, wrap_avatar=False, wrap_min_user_level=False):
    if wrap_level:
        obj['level'] = agency_service.calculate_level_by_score(obj['score'])
    if wrap_avatar and not obj['avatar']:
        obj['avatar'] = DEFAULT_AVATAR
    if obj['parent_id']:
        parent_agency = agency_service.get_agency_by_id(obj['parent_id'])
        obj['parent'] = parent_agency
    if wrap_min_user_level:
        obj['min_user_level'] = agency_stat_service.get_agency_min_user_level(obj['id'])
    return obj


def wrapper_mch_name(obj):
    mch = mch_service.get_mch(obj['mch_id'])
    obj['mch'] = mch
    return obj


def wrapper_agency_name(obj):
    agency = agency_service.get_agency_by_id(obj['agency_id'])
    if agency.get('parent_id'):
        parent_agency = agency_service.get_agency_by_id(agency['parent_id'])
        agency['parent'] = parent_agency
    obj['agency'] = agency
    return obj


def wrapper_name(obj):
    agency = agency_service.get_agency_by_id(obj['agency_id'])
    if agency.get('parent_id'):
        parent_agency = agency_service.get_agency_by_id(agency['parent_id'])
        agency['parent'] = parent_agency
    mch = mch_service.get_mch(obj['mch_id'])
    obj['agency'] = agency
    obj['mch'] = mch
    return obj
